package cn.yuanqiao.archive.storeRoom.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantYqFolder;
import cn.yuanqiao.archive.appManager.domain.TenantYqda;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.storeRoom.domain.Box;
import cn.yuanqiao.archive.storeRoom.domain.Boxspec;
import cn.yuanqiao.archive.storeRoom.domain.UpDownShelves;
import cn.yuanqiao.archive.storeRoom.mapper.BoxMapper;
import cn.yuanqiao.archive.storeRoom.mapper.BoxspecMapper;
import cn.yuanqiao.archive.storeRoom.mapper.InitializationMapper;
import cn.yuanqiao.archive.storeRoom.service.IBoxService;
import cn.yuanqiao.archive.storeRoom.util.DateUtil;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 盒-格子Service业务层处理
 *
 * @author xy
 * @date 2023-06-26
 */

@Service
public class BoxServiceImpl implements IBoxService
{
    @Autowired
    private BoxMapper boxMapper;
    @Autowired
    private BoxspecMapper boxspecMapper;
    @Autowired
    private InitializationMapper initializationMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;

    private static final Logger logger = LoggerFactory.getLogger(BoxServiceImpl.class);

    /**
     * 查询盒-格子
     *
     * @param boxId 盒-格子主键
     * @return 盒-格子
     */
    @Override
    public Box selectBoxByBoxId(Long boxId)
    {
        Box box= boxMapper.selectBoxByBoxId(boxId,SecurityUtils.getTenantCode().toUpperCase());
        String subtableName=box.getSubTableName();
        //通过表名以及boxId去获取列表
      /*  List<Map<String,Object>> list=boxMapper.getDaList(subtableName,SecurityUtils.getTenantCode().toUpperCase(),boxId);
        box.setDaList(list);*/
        return box;
    }

    /**
     * 查询盒-格子列表
     *
     * @param box 盒-格子
     * @return 盒-格子
     */
    @Override
    public List<Box> selectBoxList(Box box)
    {
        return boxMapper.selectBoxList(box);
    }

    /**
     * 新增盒-格子
     *
     * @param box 盒-格子
     * @return 结果
     */
    @Override
    public int insertBox(Box box)
    {
        box.setCreateTime(DateUtils.getNowDate());
        return boxMapper.insertBox(box);
    }

    /**
     * 修改盒-格子
     *
     * @param box 盒-格子
     * @return 结果
     */
    @Override
    public int updateBox(Box box)
    {
        return boxMapper.updateBox(box);
    }

    /**
     * 批量删除盒-格子
     *
     * @param boxIds 需要删除的盒-格子主键
     * @return 结果
     */
    @Override
    public int deleteBoxByBoxIds(Long[] boxIds)
    {
        return boxMapper.deleteBoxByBoxIds(boxIds);
    }

    /**
     * 删除盒-格子信息
     *
     * @param boxId 盒-格子主键
     * @return 结果
     */
    @Override
    public int deleteBoxByBoxId(Long boxId)
    {
        return boxMapper.deleteBoxByBoxId(boxId);
    }

    @Override
    public Map isPermit(Map map) {
        Boolean flag=true;
        Map mapResult=new HashMap();
        String type=map.get("type").toString();
        try {
            String ids = map.get("ids").toString();
            //所选择的档案门类
             String code=SecurityUtils.getTenantCode();
             if(StringUtils.isEmpty(code)){
                 //可能要抛出异常
                 throw new ServiceException("租户code不能为空！");
             }
             mapResult = boxMapper.getMapResult(Long.parseLong(map.get("categoryId").toString()), SecurityUtils.getTenantCode().toUpperCase());
            String subtablename="";
            String ajhOrJh="";
            String message="";
            if ("0".equals(type)) {
                subtablename=mapResult.get("FILE_TABLE_NAME").toString();
                ajhOrJh="JH";
                message="件号";
            } else if ("1".equals(type)) {
                subtablename=mapResult.get("FOLDER_TABLE_NAME").toString();
                ajhOrJh="AJH";
                message="案卷号";

            }
            Map<String,String> ajhOrJhString = boxMapper.getAjhOrJh(ajhOrJh,subtablename,ids);
            String ajh=ajhOrJhString.get("AJHORJH")==null?"":ajhOrJhString.get("AJHORJH");
            String [] ajhArr=ajh.split(",");
            HashSet<String> jhSet = new HashSet<String>();
            List<String> list=new ArrayList<>();
            for (String jh:ajhArr){
                if(!StringUtils.isEmpty(jh)) {
                    jhSet.add(jh);
                    list.add(jh);
                }
            }
            if(ajhArr.length!=jhSet.size()&&jhSet.size()>0){
               /* throw new ServiceException("件号相同不能一起装盒！");*/
                flag=false;
                mapResult.put("msg",message+"相同不能一起装盒！");
            }
            if(ids.split(",").length!=list.size()){
                flag=false;
                mapResult.put("msg","数据中没有"+message+"！");
            }
            mapResult.put("ajhOrJhString", ajhOrJhString.get("AJHORJH"));
            mapResult.put("ids", ajhOrJhString.get("IDS"));

            //获取选中档案的QZH以及保管期限去验证是否可以装一盒
            List<Map<String,Object>> daList=boxMapper.getDaListByIds(subtablename,ids);

            HashSet<String> qzhSet = new HashSet<String>();
            HashSet<String> bgqxSet = new HashSet<String>();

            for (int i = 0; i < daList.size(); i++) {
               Map<String,Object> daMap=daList.get(i);
               qzhSet.add(daMap.get("QZH")==null?"":daMap.get("QZH").toString());
               bgqxSet.add(daMap.get("BGQX")==null?"":daMap.get("BGQX").toString());
            }
            if(qzhSet.size()>1||bgqxSet.size()>1) {//说明至少存在两种排案卷号或者排件号规则，不允许装盒
                flag=false;
                mapResult.put("msg","选择档案保管期限或全宗号不同,不能一起装盒！");

            }

        } catch (Exception e) {
            mapResult.put("isPermit", false);
            mapResult.put("msg","装盒失败！");

            logger.error(e.getMessage(),e);
        }
        mapResult.put("isPermit", flag);
        return mapResult;

    }

    @Override
    public Map getMaxHehaoByCondition(Map map) {

        String storeroomSwitch = sysConfigService.selectConfigByKey("STOREROOM_SWITCH");
        if(StringUtils.isEmpty(storeroomSwitch)){
            throw new ServiceException("系统参数错误STOREROOM_SWITCH未找到配置！");
        }
        boolean flag=true;
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            String daIdsStr = map.get("daIdsStr").toString();
            String categoryType=map.get("type").toString();

            Map mapResult = boxMapper.getMapResult(Long.parseLong(map.get("categoryId").toString()), SecurityUtils.getTenantCode().toUpperCase());

            //String categoryType = mapResult.get("TYPE").toString();
            //所选择的档案门类
            String subtablename = "";
            if ("0".equals(categoryType)) {
                subtablename = mapResult.get("FILE_TABLE_NAME").toString();
            } else if ("1".equals(categoryType)) {
                subtablename = mapResult.get("FOLDER_TABLE_NAME").toString();
            }
            List<Map<String,Object>> daList=boxMapper.getDaListByIds(subtablename,daIdsStr);
            String qzh=daList.get(0).get("QZH").toString();
            String bgqx=daList.get(0).get("BGQX").toString();

            Integer maxHehao = boxMapper.getMaxHeHao(subtablename, qzh,bgqx, SecurityUtils.getTenantCode().toUpperCase())==null?1:boxMapper.getMaxHeHao(subtablename, qzh,bgqx, SecurityUtils.getTenantCode().toUpperCase());
            Long specId = boxMapper.getSpecId(subtablename, qzh,bgqx, SecurityUtils.getTenantCode().toUpperCase());
            resultMap.put("specId", specId);
            Boxspec boxspec = new Boxspec();
            List<Boxspec> boxSpecList = boxspecMapper.selectBoxspec(boxspec);
            resultMap.put("boxSpecList", boxSpecList);
            if(boxSpecList.size()<=0){
                resultMap.put("flag",false);
                resultMap.put("maxHehaoIsAvailable", "no");
                resultMap.put("messge", "没有盒可用!");
                return resultMap;
            }

                if (maxHehao!=null) {
                resultMap.put("maxHehao", maxHehao);
                // tiaojian+=" AND SUB_TABLE_NAME='"+subtablename+"' AND ARCHIVAL_CODE='"+substring+"'";// AND CATEGORY_ID="+mapResult.get("ID");

                Box mapResult2 = boxMapper.getMapResultByHeHao(maxHehao, subtablename, qzh,bgqx, SecurityUtils.getTenantCode().toUpperCase());
                if(mapResult2!=null&&mapResult2.getPutawayStatus()!=null) {
                    if (mapResult2.getPutawayStatus() == 2) {
                        resultMap.put("flag", true);
                        resultMap.put("specId", null);

                        resultMap.put("maxHehaoIsAvailable", "no");
                        resultMap.put("messge", "已上架，最大盒号不可用");
                        return resultMap;
                    }
                }
                if(mapResult2==null){
                    //说明这个是第一个盒子 获取当前值的最小值
                    String start="";
                    if ("0".equals(categoryType)) {
                        //件号
                        start=boxMapper.getJh(daIdsStr, subtablename, SecurityUtils.getTenantCode().toUpperCase());
                    } else if ("1".equals(categoryType)) {
                      //案卷号
                        start= boxMapper.getAjh(daIdsStr, subtablename, SecurityUtils.getTenantCode().toUpperCase());
                    }
                    resultMap.put("start", start);
                    resultMap.put("flag", true);
                    resultMap.put("maxHehaoIsAvailable", "yes");
                    resultMap.put("messge", "");
                    return resultMap;

                }
                String boxEdNum = mapResult2.getBoxEdnum()==null?"":mapResult2.getBoxEdnum().toString();
                //获取勾选的档案的最小件号/案卷号
                String selectedMinJhOrAjh = "";
                String message = "";
                if ("0".equals(categoryType)) {
                    selectedMinJhOrAjh = boxMapper.getJh(daIdsStr, subtablename, SecurityUtils.getTenantCode().toUpperCase());
                    message = "件号不连续";
                } else if ("1".equals(categoryType)) {
                    selectedMinJhOrAjh = boxMapper.getAjh(daIdsStr, subtablename, SecurityUtils.getTenantCode().toUpperCase());
                    message = "案卷号不连续";
                }
                if (mapResult2.getBoxStnum().equals(mapResult2.getBoxEdnum())) {//一件装一/多盒
                    int boxCount = boxMapper.getBoxCount(Integer.parseInt(mapResult2.getBoxStnum().toString()), maxHehao, subtablename, qzh,bgqx, Long.parseLong(mapResult.get("ID").toString()), SecurityUtils.getTenantCode().toUpperCase());
                    if (boxCount == 0) {//一件装一盒
                        if (Integer.parseInt(selectedMinJhOrAjh) - Integer.parseInt(boxEdNum) != 1) {
                            //同规则下最后一个盒中的最大件号与勾选档案的最小件号/案卷号不连续，不允许往该盒插入档案

                            resultMap.put("maxHehaoIsAvailable", "no");
                            resultMap.put("messge", message);
                        } else {
                            //同规则下最后一个盒中的最大件号与勾选档案的最小件号/案卷号连续，校验页数
                            //
                            String minDaId = "";
                            if (daIdsStr.contains(",")) {
                                String[] daIdArr = daIdsStr.split(",");
                                minDaId = daIdArr[0];
                            } else {
                                minDaId = daIdsStr;
                            }
                            if ("1".equals(storeroomSwitch)) {
                                Boxspec mapResult3 = boxspecMapper.selectBoxspecBySpecId(specId, SecurityUtils.getTenantCode().toUpperCase());
                                Integer ys = 0;
                                if ("0".equals(categoryType)) {
                                    ys = boxMapper.getYsByDa(Long.parseLong(minDaId), SecurityUtils.getTenantCode().toUpperCase());
                                } else if ("1".equals(categoryType)) {
                                    ys = boxMapper.getYsByFolder(Long.parseLong(minDaId), SecurityUtils.getTenantCode().toUpperCase());
                                }
                                if (ys != null && ((ys+mapResult2.getBoxLpage()) > mapResult3.getSpectPage())) {
                                    resultMap.put("maxHehaoIsAvailable", "no");
                                    resultMap.put("messge", "页数不够");
                                } else {
                                    resultMap.put("start", mapResult2.getBoxStnum());
                                    resultMap.put("boxEndNum", mapResult2.getBoxEdnum());
                                }
                            }else{
                                resultMap.put("start", mapResult2.getBoxStnum());
                                resultMap.put("boxEndNum", mapResult2.getBoxEdnum());
                            }
                        }
                    } else {//一件装多盒，不允许插盒
                        resultMap.put("maxHehaoIsAvailable", "no");
                        resultMap.put("messge", "一件装多盒，不允许插盒");
                    }
                } else {//多件装一盒
                    if (Integer.parseInt(selectedMinJhOrAjh) - Integer.parseInt(boxEdNum) != 1) {
                        //同规则下最后一个盒中的最大件号与勾选档案的最小件号/案卷号不连续，不允许往该盒插入档案
                        resultMap.put("maxHehaoIsAvailable", "no");
                        resultMap.put("messge", message);
                    } else {
                        //同规则下最后一个盒中的最大件号与勾选档案的最小件号/案卷号连续，校验页数
                        if ("1".equals(storeroomSwitch)) {
                            int ys = 0;
                            int ysInHe = 0;
                            if ("0".equals(categoryType)) {
                                ysInHe = boxMapper.getPageHeByDa(mapResult2.getBoxId(), SecurityUtils.getTenantCode().toUpperCase());
                                ys = boxMapper.getYsByDas(daIdsStr, SecurityUtils.getTenantCode().toUpperCase());
                            } else if ("1".equals(categoryType)) {
                                ys = boxMapper.getYsByFolders(daIdsStr, SecurityUtils.getTenantCode().toUpperCase());
                                ysInHe = boxMapper.getPageHeByFolders(mapResult2.getBoxId(), SecurityUtils.getTenantCode().toUpperCase());

                            }
                            Map<String, Object> mapResult3 = boxspecMapper.getBoxSpecMap(ysInHe, mapResult2.getSpecId(), SecurityUtils.getTenantCode().toUpperCase());
                            if (ys > Integer.parseInt(mapResult3.get("SPECT_PAGE1").toString())) {
                                resultMap.put("maxHehaoIsAvailable", "no");
                                resultMap.put("messge", "页数不够");
                            } else {
                                resultMap.put("start", mapResult2.getBoxStnum());
                                resultMap.put("boxEndNum", mapResult2.getBoxEdnum());
                            }
                        }else{
                            resultMap.put("start", mapResult2.getBoxStnum());
                            resultMap.put("boxEndNum", mapResult2.getBoxEdnum());
                        }
                    }
                }
            }
            if (!resultMap.containsKey("maxHehaoIsAvailable")) {
                resultMap.put("maxHehaoIsAvailable", "yes");

            }
            resultMap.put("flag",flag);
            return resultMap;
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            resultMap.put("flag",false);
            return resultMap;
          //  ex.printStackTrace();
        }
    }

    //此处需要改
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map saveBox(Map map) {

        String storeroomSwitch = sysConfigService.selectConfigByKey("STOREROOM_SWITCH");
        if(StringUtils.isEmpty(storeroomSwitch)){
            throw new ServiceException("系统参数错误STOREROOM_SWITCH未找到配置！");
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
           Map<String, Object> mapResult = boxMapper.getMapResult(Long.parseLong(map.get("categoryId").toString()), SecurityUtils.getTenantCode().toUpperCase());
           StringBuffer keySql = new StringBuffer();
           StringBuffer valueSql = new StringBuffer();
           String subTableName = "";
           String daIdsStr = (String) map.get("daIdsStr");
           String archivalCode = "";
           String type = map.get("type").toString();
           //需要在盒表中的  sub_table_name   存进去
            String fileTableName="";
           if ("0".equals(type)) {
               subTableName = mapResult.get("FILE_TABLE_NAME").toString();
           } else if ("1".equals(type)) {
               subTableName = mapResult.get("FOLDER_TABLE_NAME").toString();
               fileTableName=mapResult.get("FILE_TABLE_NAME").toString();
           }else if ("3".equals(type)) {
               subTableName = mapResult.get("FOLDER_TABLE_NAME").toString();
               fileTableName=mapResult.get("FILE_TABLE_NAME").toString();
           }

               List<Object> specIdList = new ArrayList<Object>();
               Set<Object> specIdSet = new HashSet<Object>();
               ArrayList<String> daIdOrFolderIdList = new ArrayList<String>();
               List<Map<String, Object>> heDataList = (List<Map<String, Object>>) map.get("heData");
               List<Map<String,Object>> daList=boxMapper.getDaListByIds(subTableName,daIdsStr);
               String qzh=daList.get(0).get("QZH").toString();
               String bgqx=daList.get(0).get("BGQX").toString();



               for (int i = 0; i < heDataList.size(); i++) {//一个个盒子

                   Map<String, Object> heData = heDataList.get(i);
                   //获取排件号/案卷号规则
                    //获取该盒子的档案id
                   String daIds=heData.get("daIds").toString();
                   Long boxId = boxMapper.getBoxId(Long.parseLong(heData.get("hehao").toString()), subTableName, qzh,bgqx, SecurityUtils.getTenantCode().toUpperCase());
                   String minNd="";
                   String maxNd="";

                   if (boxId != null) {//修改
                       Map <String,String> ndMap=boxMapper.getDaNd(subTableName,boxId,SecurityUtils.getTenantCode().toUpperCase());
                       Map <String,String> ndMap1=boxMapper.getDaNdByIds(subTableName,heData.get("daIds").toString());
                        if(Integer.parseInt(ndMap.get("MINND"))>Integer.parseInt(ndMap1.get("MINND"))){
                            minNd=ndMap1.get("MINND");
                        }else{
                            minNd=ndMap.get("MINND");
                        }
                       if(Integer.parseInt(ndMap.get("MAXND"))>Integer.parseInt(ndMap1.get("MAXND"))){
                           maxNd=ndMap.get("MAXND");
                       }else{
                           maxNd=ndMap1.get("MAXND");
                       }

                       heData.put("insertBoxId", boxId);
                       //计算剩余页数
                       //限制页数
                      Box box = boxMapper.selectBoxByBoxId(boxId, SecurityUtils.getTenantCode().toUpperCase());


                       Boxspec boxspec = boxspecMapper.selectBoxspecBySpecId(Long.parseLong(heData.get("spec_id").toString()), SecurityUtils.getTenantCode().toUpperCase());

                       Integer spectPage = boxspec.getSpectPage();
                       Integer zpage=box.getBoxLpage();


                           Integer daTotalYs = 0;
                           if ("1".equals(type)) {//组卷
                               daTotalYs = boxMapper.getPageInHeByFolders(daIds, SecurityUtils.getTenantCode().toUpperCase());
                           } else if ("0".equals(type)) {//组件
                               daTotalYs = boxMapper.getPageInHeByDa(daIds, SecurityUtils.getTenantCode().toUpperCase());
                           }
                       if("1".equals(storeroomSwitch)) {
                           if (spectPage != null && daTotalYs != null && spectPage >= (daTotalYs+zpage)) {
                               zpage = zpage + daTotalYs;
                           } else if (spectPage != null && daTotalYs != null && spectPage < (daTotalYs+zpage)) {
                               resultMap.put("flag", false);
                               resultMap.put("hehao", heData.get("hehao"));
                               resultMap.put("message", "盒号为" + heData.get("hehao") + "的档案盒页数不够，请选择其他规格的档案盒");
                               return resultMap;
                           }
                       }else{
                           zpage = zpage + daTotalYs;
                       }
                       //更新档案盒信息（包括盒子剩余页数）
                       String updateHddaBoxSql = "UPDATE " + SecurityUtils.getTenantCode().toUpperCase() + "_YQBOX SET BOX_STNUM='" + heData.get("box_stnum") + "',BOX_EDNUM='" + heData.get("box_ednum") + "',SPEC_ID=" + heData.get("spec_id") + ",HEHAO=" + heData.get("hehao") + ",BOX_STND="+minNd+",BOX_EDND="+maxNd+",BOX_LPAGE=" + zpage + " WHERE BOX_ID=" + boxId + ";";
                       keySql.append(updateHddaBoxSql);


                       //更新档案与盒的关系表信息：先删除，再重新新增
                      // String deleteHdDanganBox = "DELETE FROM " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_BOX WHERE BOX_ID=" + boxId + " AND HEHAO=" + heData.get("hehao") + " AND CATEGORY_ID=" + map.get("categoryId") + ";";
                      // keySql.append(deleteHdDanganBox);
                       //在档案与盒的关系表中新增数据
                       String insertHdDanganBoxSql = "";
                       if(daIds.indexOf(",")>-1){
                         String [] daIdArr=daIds.split(",");
                         for(String daId:daIdArr){
                             insertHdDanganBoxSql += "INSERT INTO " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_BOX (DA_ID,BOX_ID,HEHAO,SUB_TABLE_NAME,CATEGORY_ID) VALUES (" + daId + "," + boxId + "," + heData.get("hehao") + ",'" + subTableName + "'," + map.get("categoryId") + ");";
                         }
                       }else{
                           insertHdDanganBoxSql += "INSERT INTO " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_BOX (DA_ID,BOX_ID,HEHAO,SUB_TABLE_NAME,CATEGORY_ID) VALUES (" + daIds + "," + boxId + "," + heData.get("hehao") + ",'" + subTableName + "'," + map.get("categoryId") + ");";
                       }

                       keySql.append(insertHdDanganBoxSql);
                   } else {//新增
                       //
                       Map <String,String> ndMap=boxMapper.getDaNdByIds(subTableName,heData.get("daIds").toString());
                        minNd=ndMap.get("MINND");
                        maxNd=ndMap.get("MAXND");

                       String ND=(String) map.get("he_nd");
                       boxId = SnowflakeIdGenerator.generateId();
                       heData.put("insertBoxId", boxId);
                       keySql.append("INSERT INTO " + SecurityUtils.getTenantCode().toUpperCase() + "_YQBOX  (BOX_ID,PUTAWAY_STATUS,SPEC_ID,BOX_QZH,BOX_BGQX,BOX_STND,BOX_EDND");
                       valueSql.append(") VALUES(").append(boxId).append(",0");
                       valueSql.append(",").append(heData.get("spec_id"));
                       valueSql.append(",'").append(qzh);
                       valueSql.append("','").append(bgqx);
                       valueSql.append("','").append(minNd);
                       valueSql.append("','").append(maxNd);


                       //计算剩余页数
                       Boxspec boxspec = boxspecMapper.selectBoxspecBySpecId(Long.parseLong(heData.get("spec_id").toString()), SecurityUtils.getTenantCode().toUpperCase());
                       Integer spectPage = boxspec.getSpectPage();


                           Integer daTotalYs = 0;
                           if ("1".equals(type)) {//组卷
                               daTotalYs = boxMapper.getDaTotalYsByFolder(daIds, Integer.parseInt(heData.get("box_stnum").toString()), Integer.parseInt(heData.get("box_ednum").toString()), SecurityUtils.getTenantCode().toUpperCase(), subTableName);
                           } else if ("0".equals(type)) {//组件
                               daTotalYs = boxMapper.getDaTotalYsByDa(daIds, Integer.parseInt(heData.get("box_stnum").toString()), Integer.parseInt(heData.get("box_ednum").toString()), SecurityUtils.getTenantCode().toUpperCase(), subTableName);
                           }

                       if("1".equals(storeroomSwitch)) {
                           if (spectPage != null && daTotalYs != null && spectPage >= daTotalYs) {

                           } else if (spectPage != null && daTotalYs != null && spectPage < daTotalYs) {
                               resultMap.put("flag", false);
                               resultMap.put("hehao", heData.get("hehao"));
                               resultMap.put("message", "盒号为" + heData.get("hehao") + "的档案盒页数不够，请选择其他规格的档案盒");
                               return resultMap;
                           }
                       }
                       //创建信息
                       keySql.append(",BOX_LPAGE,CREATOR,CREATE_TIME,SUB_TABLE_NAME,CATEGORY_ID,BOX_STNUM,BOX_EDNUM,HEHAO");
                       valueSql.append("',").append(daTotalYs);
                       valueSql.append(",").append(SecurityUtils.getUserId());
                       valueSql.append(",'").append(DateUtil.getDateString()).append("'");
                       valueSql.append(",'").append(subTableName).append("'");
                       valueSql.append(",").append(map.get("categoryId"));
                       valueSql.append(",").append(heData.get("box_stnum"));
                       valueSql.append(",").append(heData.get("box_ednum"));
                       valueSql.append(",").append(heData.get("hehao"));

                       valueSql.append(");");
                       keySql.append(valueSql);
                       valueSql.setLength(0);

                       //关系表sql
                       String insertHdDanganBoxSql = "";
                       String start = heData.get("box_stnum").toString();
                       String end = heData.get("box_ednum").toString();

                       String [] daIdArr=daIds.split(",");
                       for(String daId:daIdArr){
                           insertHdDanganBoxSql += "INSERT INTO " + SecurityUtils.getTenantCode().toUpperCase() + "_YQDA_BOX (DA_ID,BOX_ID,HEHAO,SUB_TABLE_NAME,CATEGORY_ID) VALUES (" + daId + "," + boxId + "," + heData.get("hehao") + ",'" + subTableName + "'," + map.get("categoryId") + ");";
                       }


                       keySql.append(insertHdDanganBoxSql);

                       //更新该规格盒子的剩余个数
                       int acount = 0;
                       try {

                           acount = boxspec.getSpecAcount();
                       } catch (Exception e) {
                           acount = 0;
                       }
                       if (acount == 0) {
                           resultMap.put("flag", false);
                           resultMap.put("boxSpecACount", acount);
                           return resultMap;
                       } else {
                           specIdList.add(heData.get("spec_id"));
                           specIdSet.add(heData.get("spec_id"));
                       }

                   }
               }
               //更新该规格下可用盒子数量
               if (!StringUtils.isEmpty(specIdList) && specIdList.size() > 0) {
                   String updataHddaBoxSpecAcountSql = "";
                   for (Object specId : specIdSet) {
                       Integer specAcount = boxspecMapper.getSpecAccountById(Long.parseLong(specId.toString()), SecurityUtils.getTenantCode().toUpperCase());
                       int count = Collections.frequency(specIdList, specId);
                       if (count > specAcount) {
                           resultMap.put("flag", false);
                           resultMap.put("message", "盒子数量不够，请选择其他档案盒");
                           return resultMap;
                       }
                       updataHddaBoxSpecAcountSql += "UPDATE " + SecurityUtils.getTenantCode().toUpperCase() + "_YQBOXSPEC SET SPEC_ACOUNT=" + (specAcount - count) + " WHERE SPEC_ID=" + specId + ";";
                   }
                   keySql.append(updataHddaBoxSpecAcountSql);
               }
               //执行成功 将文件分表以及总表的状态进行修改
              String code=SecurityUtils.getTenantCode().toUpperCase();
               if(type.equals("0")){
                   //组件
                   keySql.append("UPDATE "+code+"_YQDA SET BOXSTATE=1 WHERE DA_ID IN ("+daIdsStr+");UPDATE "+subTableName+" SET BOXSTATE=1 WHERE ID IN ("+daIdsStr+");");
               }else if(type.equals("1")||type.equals("3")){
                   //组卷
                   keySql.append("UPDATE "+new TenantYqFolder().getTableName()+" SET BOXSTATE=1 WHERE FOLDER_ID IN ("+daIdsStr+") AND IS_DEL=0;UPDATE "+subTableName+" SET BOXSTATE=1 WHERE ID IN ("+daIdsStr+")  AND IS_DEL=0;");
                   //卷内件
                   keySql.append("UPDATE "+new TenantYqda().getTableName()+" SET BOXSTATE=1 WHERE DA_ID IN (select DA_ID from "+code+"_YQDA_FOLDER WHERE FOLDER_ID IN ("+daIdsStr+"))  AND IS_DEL=0;UPDATE "+fileTableName+" SET BOXSTATE=1 WHERE ID IN (select DA_ID from "+code+"_YQDA_FOLDER WHERE FOLDER_ID IN ("+daIdsStr+"))  AND IS_DEL=0;");

               }

               initializationMapper.createTable(keySql.toString());

           resultMap.put("flag", true);
           return resultMap;
       }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            resultMap.put("flag", false);
            return resultMap;
          // throw new ServiceException("装盒失败！");

       }
    }

    @Override
    public Map updateBoxNumber(Map map) {
        Map<String,Object> resultMap=new HashMap<String,Object>();
        boolean result = true;
        try {
            String daIdsStr=map.get("daIdsStr").toString();
            String type=map.get("type").toString();
            Map<String, Object> mapResult = boxMapper.getMapResult(Long.parseLong(map.get("categoryId").toString()), SecurityUtils.getTenantCode().toUpperCase());
            //获取档号去掉案卷号或者件号后的部分
            String subTableName ="";
            if ("0".equals(type)) {
                subTableName=mapResult.get("FILE_TABLE_NAME").toString();
            } else if ("1".equals(type)) {
                subTableName=mapResult.get("FOLDER_TABLE_NAME").toString();
            }
            List<Map<String,Object>> daList=boxMapper.getDaListByIds(subTableName,daIdsStr);
            String qzh=daList.get(0).get("QZH").toString();
            String bgqx=daList.get(0).get("BGQX").toString();
            List<Box> daBoxList = boxMapper.getDaBoxList(qzh,bgqx,subTableName,SecurityUtils.getTenantCode().toUpperCase());
            //如果勾选档案的档号规则下存在已经上架的档案盒，提示用户先下架再重排
            for (int i = 0; i < daBoxList.size(); i++) {
                if("2".equals(daBoxList.get(i).getPutawayStatus().toString())) {
                    resultMap.put("message", "盒号为"+daBoxList.get(i).getHehao()+"的档案盒已上架，请先下架再重排盒号");
                    resultMap.put("result", false);
                    return resultMap;
                }
            }
            Collections.sort(daBoxList, new Comparator<Box>() {
                @Override
                public int compare(Box o1, Box o2) {
                    return Integer.valueOf(o1.getBoxStnd()).compareTo(Integer.valueOf(o2.getBoxStnd()));
                }
            });
            StringBuffer updateSql = new StringBuffer();
            int hehao = 1;
            for (int i = 0; i < daBoxList.size(); i++) {
                StringBuffer updateHddaBoxSql = new StringBuffer();
                StringBuffer updateHddanganBoxSql = new StringBuffer();

                updateHddaBoxSql.append("UPDATE "+SecurityUtils.getTenantCode().toUpperCase()+"_YQBOX SET HEHAO='"+hehao+"' WHERE BOX_ID="+daBoxList.get(i).getBoxId()+";");
                updateHddanganBoxSql.append("UPDATE "+SecurityUtils.getTenantCode().toUpperCase()+"_YQDA_BOX SET HEHAO='"+hehao+"' WHERE BOX_ID="+daBoxList.get(i).getBoxId()+";");

                updateSql.append(updateHddaBoxSql).append(updateHddanganBoxSql);

                hehao++;
            }

          initializationMapper.createTable(updateSql.toString());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            resultMap.put("result",false);
            return resultMap;
        }
        resultMap.put("result",result);
        return resultMap;
    }

    @Override
    public Map cancelBox(Map parameterMap) {

        String code=SecurityUtils.getTenantCode().toUpperCase();


        Map<String, Object> resultMap = new HashMap<String,Object>();
        StringBuffer sql = new StringBuffer();
        String updateDaSql="";
        boolean result = true;
        String ids = parameterMap.get("ids").toString();
        Map<String, Object> mapResult = boxMapper.getMapResult(Long.parseLong(parameterMap.get("categoryId").toString()), code);

        String type = parameterMap.get("type").toString();
        //需要在盒表中的  sub_table_name   存进去
        String tableName="",subtablename="",jnjTableName="",ajhOrJh="",message="",message1="";
        if("1".equals(type)) {
            subtablename = mapResult.get("FOLDER_TABLE_NAME").toString();
            jnjTableName = mapResult.get("FILE_TABLE_NAME").toString();
            ajhOrJh="AJH";
            message1="案卷号";
        }else if("0".equals(type)) {
            subtablename =mapResult.get("FILE_TABLE_NAME").toString();
            ajhOrJh="JH";
            message1="件号";
        }else if("3".equals(type)) {
            subtablename = mapResult.get("FOLDER_TABLE_NAME").toString();
            jnjTableName = mapResult.get("FILE_TABLE_NAME").toString();
            ajhOrJh="AJH";
            message1="案卷号";
        }
        //第一种情况：选择的档案已上架，不允许取消装盒
        String putawayStatusString =boxMapper.getPutawayStatus(ids,Long.parseLong(parameterMap.get("categoryId").toString()),code);
        //已上架，不允许取消装盒
        if (!StringUtils.isEmpty(putawayStatusString) && putawayStatusString.contains("2")) {
            resultMap.put("isPermit", false);
            resultMap.put("message", "选择的档案中存在已上架档案，请先下架再操作");
            return resultMap;
        }
        //获取排件号/案卷号规则
        List<Map<String,Object>> listResult1 = boxMapper.getDhMessageList(ajhOrJh,subtablename,ids);
        //给多个档案装一个盒用的
        Map<String,Map<String, Object>> multMap = new HashMap<String,Map<String,Object>>();
        for (int i = 0; i < listResult1.size(); i++) {
            //循环拿到所选择的每个档案的排案卷号/排件号规则，加上subtablename，用这两个条件去找档案盒
          //  String substring = listResult1.get(i).get("DH").substring(0, lastIndexOf);
            String id = listResult1.get(i).get("ID").toString();
            String single3 = listResult1.get(i).get("AJHORJH").toString();
            String qzh=listResult1.get(i).get("QZH").toString();
            String bgqx=listResult1.get(i).get("BGQX").toString();
            //一个件装多个盒；一个件装一个盒；多个件装一个盒
            //如果选择的档案的件号在档案盒中连续件号中不属于第一个/最后一个，重新装盒删除件号会造成所在盒的件号不连续，这种情况不允许重新装盒
            ArrayList<String> boxIdList = boxMapper.getBoxIdByDaId(id,subtablename,code);
            ArrayList<String> daIdList = new ArrayList<String>();
            if (boxIdList!=null&& boxIdList.size() > 1) {//一件装多盒，可以直接清空盒号
                //直接删除HDDANGAN_BOX表、HDDABOX表的数据
                String boxIdListString = boxIdList.toString().substring(1, boxIdList.toString().length()-1);
                String deleteHdDanganBoxSql = "DELETE FROM "+code+"_YQDA_BOX WHERE BOX_ID IN ("+boxIdListString+");";
                //清空档案的盒号
                String deleteHddaBoxSql = "DELETE FROM "+code+"_YQBOX WHERE BOX_ID IN ("+boxIdListString+");";
                sql.append(deleteHdDanganBoxSql).append(updateDaSql).append(deleteHddaBoxSql);
            }else if (boxIdList!=null&& boxIdList.size() == 1) {//一件装一个盒或者多个件装一个盒，需要进一步判断
                String paixu="";
                if("1".equals(type)) {
                    paixu="AJH";
                }else if("0".equals(type)) {
                    paixu = "JH";
                }
                daIdList =boxMapper.getDaIdList(subtablename,Long.parseLong(boxIdList.get(0)),paixu,code);
                if(daIdList.size() == 1) {//一个件装一个盒，可以直接清空盒号
                    //直接删除HDDANGAN_BOX表、HDDABOX表的数据
                    String deleteHdDanganBoxSql = "DELETE FROM "+code+"_YQDA_BOX WHERE BOX_ID="+boxIdList.get(0)+";";
                    String deleteHddaBoxSql = "DELETE FROM  "+code+"_YQBOX WHERE BOX_ID="+boxIdList.get(0)+";";
                    String specSql =  "UPDATE "+code+"_YQBOXSPEC SET SPEC_ACOUNT= SPEC_ACOUNT+1 WHERE SPEC_ID=(SELECT nvl(SPEC_ID,-1) FROM "+code+"_YQBOX WHERE BOX_ID="+boxIdList.get(0)+");";
                    sql.append(specSql);
                    sql.append(deleteHdDanganBoxSql).append(updateDaSql).append(deleteHddaBoxSql);

                }else if(daIdList.size() > 1) {//多个件装一个盒，判断件号位置，只有位于0和末尾才可以清空盒号，其他位置清空盒号会造成该盒所装档案件号不连续，不允许这样操作
                    Map<String, Object> mapResult2 = boxMapper.getBoxMapByBoxId(Long.parseLong(boxIdList.get(0)),code);
                   if(!multMap.containsKey(mapResult2.get("BOX_ID").toString())) {
                        multMap.put(boxIdList.get(0), mapResult2);
                    }
                    if(single3.equals(multMap.get(boxIdList.get(0)).get("BOX_STNUM").toString())) {
                        Map<String, Object> map = multMap.get(boxIdList.get(0));
                        map.put("BOX_STNUM",Integer.parseInt(multMap.get(boxIdList.get(0)).get("BOX_STNUM").toString())+1);
                    }else if(single3.equals(multMap.get(boxIdList.get(0)).get("BOX_EDNUM").toString())) {
                        Map<String, Object> map = multMap.get(boxIdList.get(0));
                        map.put("BOX_EDNUM",Integer.parseInt(multMap.get(boxIdList.get(0)).get("BOX_EDNUM").toString())-1);
                    }else {
                        //存在一种情况：这次选的两个档案是盒里的最后两个档案，这时判断盒里最后一个档案的id是否在这次勾选的id里面
                        //勾选的档案是否连续，是否是档案盒里的最后几个连续档案
                        String ids1=boxMapper.getIds(subtablename,qzh,bgqx,ids,ajhOrJh,Integer.parseInt(mapResult2.get("BOX_EDNUM").toString()),single3);
                        //档案盒里的最后几个连续档案id
                        String ids2=boxMapper.getIdMessage(subtablename,qzh,bgqx,ajhOrJh,Integer.parseInt(mapResult2.get("BOX_EDNUM").toString()),single3);
                        if(ids1.equals(ids2)) {
                            //由于该排件号规则下，下一个档案的件号肯定比当前档案的件号大，所以与盒的止件号进行比较，避免循环到下一个档案时又将止件号越改越大
                            if(Integer.parseInt(single3)<=Integer.parseInt(mapResult2.get("BOX_EDNUM").toString())) {
                                mapResult2.put("BOX_EDNUM",Integer.parseInt(single3)-1);
                            }
                        }else {
                            resultMap.put("isPermit", false);
                            message="选择的档案中存在处于档案盒中间位置的档案，取消装盒会造成档案盒的起止"+message1+"不连续，请重新选择";
                            resultMap.put("message", message);
                            return resultMap;
                        }
                    }
                }
            }
        }
        StringBuffer sql2=new StringBuffer();
        if(!multMap.isEmpty()) {
            for(String key:multMap.keySet()) {
                Map<String, Object> map = multMap.get(key);
                int parseInt = Integer.parseInt(map.get("BOX_STNUM").toString());
                int parseInt2 = Integer.parseInt(map.get("BOX_EDNUM").toString());
                if(parseInt>parseInt2) {//删除盒

                    //更新剩余盒子数量和剩余页数
                    sql2.append("UPDATE "+code+"_YQBOXSPEC SET SPEC_ACOUNT=SPEC_ACOUNT+1 WHERE SPEC_ID="+map.get("SPEC_ID")+";");
                    sql2.append("DELETE FROM "+code+"_YQBOX WHERE BOX_ID="+map.get("BOX_ID")+";DELETE FROM "+code+"_YQDA_BOX WHERE BOX_ID="+map.get("BOX_ID")+";");

                }else {//更新盒
                    int ys=0;
                    String idss="";
                    if(!map.get("BOX_STNUM").toString().equals(map.get("OLD_BOX_STNUM").toString())) {
                        if("1".equals(type)) {
                            ys+=boxMapper.getSumYsByFolder(jnjTableName,subtablename,Long.parseLong(map.get("BOX_ID").toString()),Integer.parseInt(map.get("OLD_BOX_STNUM").toString()),Integer.parseInt(map.get("BOX_STNUM").toString()),SecurityUtils.getTenantCode().toUpperCase());
                        }else if("0".equals(type)) {
                            ys+=boxMapper.getSumYsByDa(subtablename,Long.parseLong(map.get("BOX_ID").toString()),SecurityUtils.getTenantCode().toUpperCase(),Integer.parseInt(map.get("OLD_BOX_STNUM").toString()),Integer.parseInt(map.get("BOX_STNUM").toString()));

                        }
                        idss = boxMapper.getIdss(subtablename,Long.parseLong(map.get("BOX_ID").toString()),SecurityUtils.getTenantCode().toUpperCase(),ajhOrJh,Integer.parseInt(map.get("OLD_BOX_STNUM").toString()),Integer.parseInt(map.get("BOX_STNUM").toString()));

                    }
                    if(!map.get("BOX_EDNUM").toString().equals(map.get("OLD_BOX_EDNUM").toString())) {
                        if("1".equals(type)) {
                            //例如：止件号从9改成了7
                            ys+=boxMapper.getSumYsByBoxEndNum(jnjTableName,subtablename,Long.parseLong(map.get("BOX_ID").toString()),Integer.parseInt(map.get("OLD_BOX_EDNUM").toString()),Integer.parseInt(map.get("BOX_EDNUM").toString()),SecurityUtils.getTenantCode().toUpperCase());
                        }else if("0".equals(type)) {

                            ys+=boxMapper.getSumDaYsByBoxEndNum(subtablename,Long.parseLong(map.get("BOX_ID").toString()),SecurityUtils.getTenantCode().toUpperCase(),Integer.parseInt(map.get("OLD_BOX_EDNUM").toString()),Integer.parseInt(map.get("BOX_EDNUM").toString()));
                        }
                        String single=boxMapper.getIdssByBoxEdNum(subtablename,Long.parseLong(map.get("BOX_ID").toString()),SecurityUtils.getTenantCode().toUpperCase(),ajhOrJh,Integer.parseInt(map.get("OLD_BOX_EDNUM").toString()),Integer.parseInt(map.get("BOX_EDNUM").toString()));
                        if(StringUtils.isEmpty(idss)) {
                            idss=single;
                        }else {
                            idss+=","+single;
                        }
                    }
                    //判断盒子里的idss的最大年限与最小年限进行对比修改 BOX_STND ,
                    //        BOX_EDND
                    String syIds=boxMapper.getSyIds(map.get("BOX_ID")==null?"":map.get("BOX_ID").toString(),idss,code);
                    Map<String,String> ndMap=new HashMap();
                    if(!StringUtils.isEmpty(syIds)){
                       ndMap=boxMapper.getDaNdByIds(subtablename,syIds);

                    }
                    boxMapper.getDaNdByIds(subtablename,idss);
                    if (ndMap != null) {
                        String minNd=ndMap.get("MINND");
                        String maxNd=ndMap.get("MAXND");
                        sql2.append("UPDATE " + code + "_YQBOX SET BOX_STNUM='" + map.get("BOX_STNUM") + "',BOX_EDNUM='" + map.get("BOX_EDNUM") + "',BOX_LPAGE=BOX_LPAGE-" + ys + ",BOX_STND='"+minNd+"',BOX_EDND='"+maxNd+"' WHERE BOX_ID=" + map.get("BOX_ID") + ";");
                        sql2.append("DELETE FROM " + code + "_YQDA_BOX WHERE DA_ID IN(" + idss + ") AND SUB_TABLE_NAME='" + subtablename + "';");

                    }else {

                        //获取原来的最大和最小的值
                        sql2.append("UPDATE " + code + "_YQBOX SET BOX_STNUM='" + map.get("BOX_STNUM") + "',BOX_EDNUM='" + map.get("BOX_EDNUM") + "',BOX_LPAGE=BOX_LPAGE-" + ys + " WHERE BOX_ID=" + map.get("BOX_ID") + ";");
                        sql2.append("DELETE FROM " + code + "_YQDA_BOX WHERE DA_ID IN(" + idss + ") AND SUB_TABLE_NAME='" + subtablename + "';");
                    }
                    }
            }
        }
        sql.append(sql2);
        try {
            //执行成功 将文件分表以及总表的状态进行修改
            if(type.equals("0")){
                //组件
                sql.append("UPDATE "+code+"_YQDA SET BOXSTATE=0 WHERE DA_ID IN ("+ids+");UPDATE "+subtablename+" SET BOXSTATE=0 WHERE ID IN ("+ids+");");
            }else if(type.equals("1")||type.equals("3")){
                //组卷
                sql.append("UPDATE "+new TenantYqFolder().getTableName()+" SET BOXSTATE=0 WHERE FOLDER_ID IN ("+ids+") AND IS_DEL=0;UPDATE "+subtablename+" SET BOXSTATE=0 WHERE ID IN ("+ids+")  AND IS_DEL=0;");
                //卷内件
                sql.append("UPDATE "+new TenantYqda().getTableName()+" SET BOXSTATE=0 WHERE DA_ID IN (select DA_ID from "+code+"_YQDA_FOLDER WHERE FOLDER_ID IN ("+ids+"))  AND IS_DEL=0;UPDATE "+jnjTableName+" SET BOXSTATE=0 WHERE ID IN (select DA_ID from "+code+"_YQDA_FOLDER WHERE FOLDER_ID IN ("+ids+"))  AND IS_DEL=0;");

            }
        initializationMapper.createTable(sql.toString());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            resultMap.put("isPermit", false);
            return resultMap;
        }
        resultMap.put("isPermit", true);
        return resultMap;
    }

    @Override
    public Boolean getFlag(String daIds, String type) {
        boolean flag=false;
       //装盒
        if("0".equals(type)){
            int count=boxMapper.getCount(daIds,SecurityUtils.getTenantCode().toUpperCase());
            flag= count <= 0;
        }else if("1".equals(type)){
         //取消装盒
           List <String>daIdArr=Arrays.asList(daIds.split(","));
            int count=boxMapper.getCount(daIds,SecurityUtils.getTenantCode().toUpperCase());
            flag= count >= daIdArr.size();


        }

        return flag;
    }
    @Override
    public List<UpDownShelves> selectList(Box box) {
        return boxMapper.selectList(box.getBoxBgqx(), box.getHehao(), box.getCategoryId(), SecurityUtils.getTenantCode());
    }
}
